package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Client;
import org.ahuanlien.crm.domain.ClientDevelop;
import org.ahuanlien.crm.domain.Employee;
import org.ahuanlien.crm.mapper.ClientDevelopMapper;
import org.ahuanlien.crm.mapper.ClientMapper;
import org.ahuanlien.crm.query.ClientDevelopQueryObject;
import org.ahuanlien.crm.service.IClientDevelopService;
import org.ahuanlien.crm.util.PageResult;
import org.ahuanlien.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ClientDevelopServiceImpl implements IClientDevelopService {

	@Autowired
	private ClientDevelopMapper clientDevelopMapper;

	@Autowired
	private ClientMapper clientMapper;

	public PageResult Query(ClientDevelopQueryObject qo) {
		Integer state = qo.getState();
		if (state == 0) {
			int count = clientDevelopMapper.developQueryForCount(qo);
			if (count == 0) {
				return new PageResult(count, Collections.EMPTY_LIST);
			}
			List<ClientDevelop> result = clientDevelopMapper.developQueryForList(qo);
			return new PageResult(count, result);

		} else if (state == 2) {
			int count = clientDevelopMapper.followUpQueryForCount(qo);
			if (count == 0) {
				return new PageResult(count, Collections.EMPTY_LIST);
			}
			List<ClientDevelop> result = clientDevelopMapper.followUpQueryForList(qo);
			return new PageResult(count, result);
		}
		return null;
	}

	public void saveOrUpdate(ClientDevelop record) {
		if (record.getId() != null) {
            Client client = clientMapper.selectByPrimaryKey(record.getClientId());
            Employee currentUser = UserContext.getCurrentUser();
            record.setCreateEmp(currentUser.getUsername());
            record.setState(client.getState());
            record.setClientName(client.getClientName());
			clientDevelopMapper.updateByPrimaryKey(record);
		} else {
			Client client = clientMapper.selectByPrimaryKey(record.getClientId());
            Employee currentUser = UserContext.getCurrentUser();
            record.setCreateEmp(currentUser.getUsername());
			record.setState(client.getState());
			record.setClientName(client.getClientName());
			clientDevelopMapper.insert(record);
		}
	}

    public void deleteRecordById(Long id) {
	    clientDevelopMapper.deleteByPrimaryKey(id);
    }

    public void changeResult(Long id,Long result) {
        clientDevelopMapper.changeResult(id,result);
    }
}
